<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="exportEmployees()"
          >excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" prop="staffPhoto">
            <template #default="{row}" width="100">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="width:100%"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="correctionTime" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?userId=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="doAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="page"
            :page-size="size"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addor-edit
          @close="showDialog=false"
          @success="success"
        />
      </el-dialog>
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 查看角色 -->
      <el-dialog title="分配角色" :visible.sync="showAssignRole">
        <assignRole
          v-if="showAssignRole"
          :cur-id="curId"
          @close="showAssignRole=false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignRole from './assignRole.vue'
import QrCode from 'qrcode'
import addorEdit from './empDialog'
import { delEmployees, getEmployees } from '@/api/employees'
import employeesNums from '@/constant/employees'
const obj = employeesNums.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: { addorEdit, assignRole },
  data() {
    return {
      list: [],
      page: 1,
      size: 10,
      total: 0,
      showDialog: false,
      showCodeDialog: false,
      showAssignRole: false,
      curId: ''
    }
  },
  created() {
    this.loadgetEmployees()
  },
  methods: {
    // 分配员工角色
    async doAssignRole(id) {
      this.showAssignRole = true
      this.curId = id
    },
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 实现导出excel
    exportEmployees() {
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        const { tHeader, data } = this.transZhKeyToexcel(this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transZhKeyToexcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      if (!list[0]) return
      // 转化出一个中文表头
      const tHeader = Object.keys(list[0]).map(enKey => {
        return mapInfo[enKey]
      })
      // 将单个数据转化为数组形式
      const data = list.map(item => {
        return Object.keys(item).map(enkey => {
          return item[enkey]
        })
      })
      return { tHeader, data }
    },
    async hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        if (res.code !== 10000) return
        this.$message.success(res.message)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadgetEmployees()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    success() {
      this.showDialog = false
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadgetEmployees()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadgetEmployees()
    },
    formData(val) {
      return obj[val]
    },
    async loadgetEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        // console.log('', res)
        if (res.code !== 10000) return
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
        // 保存数据
      } catch (err) {
        console.log('', err)
      }
    }
  }
}
</script>
